package org.dant.ant.extension.net.processors;

import java.io.*;
import java.util.*;

public class OutputChecker implements Runnable {

  private InputStream stdout;
  private CheckThread checker;

  protected List expectStream = new ArrayList();
  protected boolean finished = true;
  protected StringBuffer outBuffer = new StringBuffer();

  public OutputChecker(CheckThread checker) {
    this.checker = checker;
  }

  public void run() {
    try {
      System.out.println("std.out checker started");
      checkStdOutput();
      System.out.println("std.out checker finished");
    } catch (IOException ioe) {
      checker.setSucceed(false);
      ioe.printStackTrace();
    }
  }

  public void addExpectStream(String out) {
    expectStream.add(out);
  }

  public void setProcessInputStream(InputStream is) {
    this.stdout = is;
  }

  public StringBuffer getOutputBuffer() {
    return this.outBuffer;
  }

  public boolean isFinished() {
    return this.finished;
  }
  
  private void checkStdOutput() throws IOException {
    InputStreamReader isr = new InputStreamReader (stdout);
    BufferedReader br = new BufferedReader (isr);
    String s = br.readLine ();
    while(s != null) {
      System.out.println("out line- " + s);
      
      outBuffer.append(s);
      outBuffer.append("\n");

      if (finished && assertExpected(s)) {
        System.out.println(" expected std.out string <" + s + ">  occurs, notify the executor, and return back to the client");
        finished = false;
        checker.notifyExe();
      }

      s = br.readLine();
    }
    
    br.close();
    isr.close();
    stdout.close();
  }

  public boolean assertExpected(String line) {
    for(Iterator iter=expectStream.iterator(); iter.hasNext();) {
      String expect = (String) iter.next();
      if (line.indexOf(expect) != -1) {
        return true;
      }
    }
    return false;
  }
}
